package com.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.dto.CommentReplyFormDTO;
import com.demo.dto.Result;
import com.demo.entity.CommentReply;
import com.demo.mapper.CommentReplyMapper;
import com.demo.service.CommentReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.utils.SystemConstants;
import com.demo.utils.UserHolder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Zeng
 * @since 2022-03-23
 */
@Service
public class CommentReplyServiceImpl extends ServiceImpl<CommentReplyMapper, CommentReply> implements CommentReplyService {

    @Override
    public Result<CommentReply> postCommentReply(CommentReplyFormDTO replyFormDTO) {
        CommentReply commentReply = BeanUtil.copyProperties(replyFormDTO, CommentReply.class);
        Integer userId = UserHolder.getUser().getUserId();
        commentReply.setUserFrom(userId);
        try {
            save(commentReply);
            return Result.ok(getById(commentReply.getCmReplyId()), "新建回复成功");
        } catch (Exception e) {
            return Result.fail("新建回复失败");
        }
    }

    @Override
    public Result<CommentReply> deleteCommentReply(Integer cmReplyId) {
        // 查看该用户有没有发表这个回复
        Integer userId = UserHolder.getUser().getUserId();
        CommentReply commentReply = query().eq("user_from", userId)
                .eq("cm_reply_id", cmReplyId).one();
        if (commentReply == null) {
            // 没发表
            return Result.fail("用户没有发表这个评论，无法删除");
        }
        removeById(cmReplyId);
        return Result.ok(commentReply, "评论删除成功");
    }

    @Override
    public Result<List<CommentReply>> getReplyListByCommentId(Integer commentId, Integer current) {
        List<CommentReply> replyList = query().eq("comment_id", commentId)
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE)).getRecords();
        return Result.ok(replyList);
    }
}
